# -*- coding: utf-8 -*-
from typing import Optional, Awaitable
import tornado.web
import tornado.escape
import json
import os
from qa_engine import QAEngine
from const import RESOURCE_PATH


class MainHandler(tornado.web.RequestHandler):

    # TODO: 因为每次收到一个请求都会生成一个MainHandler对象, 所以为了避免重复载入,
    #  先作为类静态对象
    qa_engine = QAEngine(os.path.join(RESOURCE_PATH, 'main-engine.yml'))

    def __init__(
            self, application, request, **kwargs
    ):
        super().__init__(application, request, **kwargs)

    def post(self):
        """
        处理post请求方法
        :return:
        """
        # TODO: target参数可以放到URL里
        target = self.get_argument('target')
        try:
            post_data = json.loads(self.request.body, strict=False)
        except json.decoder.JSONDecodeError:
            self.write(json.dumps({'error': 'error data form'}))
            return
        if target == 'graph_qa':
            self.write(self.handle_qa(post_data['question']))
        elif target == 'recognition':
            MainHandler.handle_recognition()
        else:
            self.write(json.dumps({'error': 'unknown target'}))

    @staticmethod
    def handle_recognition():
        """
        处理人脸识别请求的方法
        :return:
        """
        # user = User()
        # print('post_data', post_data)
        # age = post_data['age']
        # # age = age.decode('utf-8')
        # sex = post_data['sex']
        # # sex = sex.decode('utf-8')
        # img = post_data['img']
        # if age == '未知':
        #     age = None
        # if sex == '未知':
        #     sex = None
        # if img == '未知':
        #     img = None
        #
        # img_data = base64.b64decode(img)
        # img_id = '{0:%Y%m%d%H%M%S%f}'.format(datetime.datetime.now())
        #
        # with open(img_id + '.jpg', 'wb') as f:
        #     f.write(img_data)
        # user.set_sex(sex)
        # user.set_age(age)
        # GeneralHub.set_user(user)
        # res_dict = {'response': '已连接'}
        # res_json = json.dumps(res_dict)
        # print(res_json)
        # self.write(res_json)
        # print('age,sex', age, sex)
        raise NotImplementedError

    def handle_qa(self, question: str):
        """
        处理问答请求的方法
        :param question: 问句
        :return: 返回客户端的json
        """
        # TODO: 目前用户系统完全没有实现: 首先需要将问句和用户对应起来, 然后根据用户
        #  之前的输入选择对应的回答
        responses = self.qa_engine.response(None, question)

        if len(responses) == 2:
            res_dict = {
                'first': str(responses[0]), 'second': responses[1]
            }
        elif len(responses) == 1:
            res_dict = {'first': str(responses[0])}
            if responses[0] == '' or str(responses[0]).find('抱歉') != -1:
                with open('question-cannot-handle.txt', 'a') as file:
                    file.writelines(question)
                    file.writelines('\n')
        elif len(responses) == 3:
            with open('question-cannot-handle.txt', 'a') as file:
                file.writelines(responses[0])
                file.writelines('\n')
            res_dict = {'first': '收到'}
        else:
            res_dict = {'error': 'unexpected case.'}
        res_json = json.dumps(res_dict)
        return res_json

    def set_default_headers(self):
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
        self.set_header('Access-Control-Max-Age', 1000)
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Content-type', 'application/json')

    def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]:
        raise NotImplementedError
